package com.bayair.doctor.ui.main.right;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.allen.library.SuperTextView;
import com.bayair.common.BaseDialog;
import com.bayair.doctor.App;
import com.bayair.doctor.R;
import com.bayair.doctor.biz.helper.SpSetting;
import com.bayair.doctor.mvp.BaseMVPFragment;
import com.bayair.doctor.mvp.annotation.InjectPresenter;
import com.bayair.doctor.biz.helper.SpDoctor;
import com.bayair.doctor.ui.login.LoginActivity;
import com.bayair.doctor.utils.MultiQuickClick;
import com.bayair.doctor.utils.log.KLog;
import com.bayair.doctor.widget.dialog.InputDialog;
import com.bayair.doctor.widget.dialog.MenuDialog;
import com.bayair.doctor.widget.dialog.MessageDialog;
import com.bayair.doctor.widget.dialog.ToastDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.wildma.pictureselector.PictureSelectUtils;
import com.wildma.pictureselector.PictureSelector;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

public class RightFragment extends BaseMVPFragment implements RightContract.View {


    public static RightFragment newInstance() {
        RightFragment myFragment = new RightFragment();
        return myFragment;
    }

    @BindView(R.id.fl_me_head_bg)
    FrameLayout mRlHeadBg;
    @BindView(R.id.iv_me_head)
    ImageView mIvHead;
    @BindView(R.id.tv_me_nikename)
    TextView tvNikeName;
    @BindView(R.id.stv_me_modify_nikename)
    SuperTextView stvModifyNikename;
    @BindView(R.id.stv_me_received_msg)
    SuperTextView stvReceivedMsg;
    @BindView(R.id.stv_me_inquiry)
    SuperTextView stvInquiry;
    @BindView(R.id.btn_me_logout)
    TextView btnLogout;

    private String mIconUrl;


    @InjectPresenter
    RightPresenter mPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_right;
    }

    @Override
    protected boolean statusBarDarkFont() {
        return true;
    }

    @Override
    protected void initView() {
        stvReceivedMsg.setSwitchIsChecked(SpDoctor.isReceive());
        stvInquiry.setSwitchIsChecked(SpDoctor.isInquiry());

        getInfoFromLocal();
    }

    @Override
    protected void initData() {
    }


    SuperTextView.OnSwitchCheckedChangeListener receiveMsgSwitchListener = (buttonView, isChecked) -> {
        if (MultiQuickClick.isMultiClick()) {
            showWarning("请您不要频繁切换");
        } else {
            toast("正在保存...");
            addLoadingToView(stvReceivedMsg);
            mPresenter.setReceive(isChecked);
        }
    };
    SuperTextView.OnSwitchCheckedChangeListener inquirySwitchListener = (buttonView, isChecked) -> {
        if (MultiQuickClick.isMultiClick()) {
            showWarning("请您不要频繁切换");
        } else {
            toast("正在保存...");
            addLoadingToView(stvInquiry);
            mPresenter.setInquiry(isChecked);
        }
    };

    @Override
    protected void setListener() {
        stvModifyNikename.setOnSuperTextViewClickListener(superTextView -> {
            String rightString = superTextView.getRightString();
            //显示修改输入弹窗
            showInputDialog(rightString);
        });

        //
        stvReceivedMsg.setOnSuperTextViewClickListener(superTextView ->
                superTextView.setSwitchIsChecked(!superTextView.getSwitchIsChecked())
        ).setSwitchCheckedChangeListener(receiveMsgSwitchListener);

        stvInquiry.setOnSuperTextViewClickListener(superTextView ->
                superTextView.setSwitchIsChecked(!superTextView.getSwitchIsChecked())
        ).setSwitchCheckedChangeListener(inquirySwitchListener);

        mIvHead.setOnClickListener(v -> {
            if (!NetworkUtils.isConnected()) {
                toast("网络不给力，请检查网络设置。");
            } else {
                //showMenuChoose();
                PictureSelector
                        .create(this, PictureSelector.SELECT_REQUEST_CODE)
                        .selectPicture(true, 480, 480, 1, 1);
            }
        });

        btnLogout.setOnClickListener(v -> {
//            mIconUrl = String.format("https://picsum.photos/id/%d/200/200", new Random().nextInt(1000));
//            updatePic();
            showMessage();
        });
    }

    @Override
    public void onVisible() {
        super.onVisible();
        KLog.d("Right onVisible 可见");

        getInfoFromServer();
    }

    private void getInfoFromLocal() {
        /**
         获取本地保存的用户自己的资料
         */
        TIMUserProfile profile = TIMFriendshipManager.getInstance().querySelfProfile();
        KLog.d("本地存储用户信息：" + profile);
        if (profile != null) {
            mIconUrl = profile.getFaceUrl();
            if (!TextUtils.isEmpty(mIconUrl)) {
                //加载头像、背景
                setImageIntoView();
            }
            String nickName = profile.getNickName();
            if (!TextUtils.isEmpty(nickName)) {
                stvModifyNikename.setRightString(nickName);
            }

        } else {
            mIconUrl = SpDoctor.getFACE_URL();
            if (!TextUtils.isEmpty(mIconUrl)) {
                //设置头像、背景
                setImageIntoView();
            } else {

            }
        }
    }

    private void getInfoFromServer() {
        /**
         获取服务器保存的用户自己的资料
         */
        TIMFriendshipManager.getInstance().getSelfProfile(new TIMValueCallBack<TIMUserProfile>() {
            @Override
            public void onError(int i, String s) {
                log("SelfProfile onError code=" + i + ", desc=" + s);
                mIvHead.setImageResource(R.drawable.me_head);
            }

            @Override
            public void onSuccess(TIMUserProfile profile) {
                log("Profile onSuccess :" + profile);
                mIconUrl = profile.getFaceUrl();
                if (!TextUtils.isEmpty(mIconUrl)) {
                    //加载头像、背景
                    setImageIntoView();
                }
                String nickName = profile.getNickName();
                if (!TextUtils.isEmpty(nickName)) {
                    stvModifyNikename.setRightString(nickName);
                }
            }
        });
    }


    private void addLoadingToView(View view) {
        if (view instanceof SuperTextView) {
            SuperTextView superTextView = (SuperTextView) view;
            superTextView.setRightIcon(R.drawable.loading_icon);
            superTextView.getRightIconIV().startAnimation(AnimationUtils.loadAnimation(App.getContext(), R.anim.image_rotate));
            superTextView.setSwitchCheckedChangeListener(null);
            superTextView.getSwitch().setEnabled(false);
            superTextView.setEnabled(false);
        }
    }

    private void completeView(View view) {
        if (view instanceof SuperTextView) {
            SuperTextView superTextView = (SuperTextView) view;
            superTextView.setRightIcon(null);
            superTextView.getSwitch().setEnabled(true);
            superTextView.setEnabled(true);
        }
    }




    void showInputDialog(String nikename) {
        // 输入对话框
        InputDialog.Builder dialog = new InputDialog.Builder(getAttachActivity())
                // 标题可以不用填写
                .setTitle("修改昵称")
                // 内容可以不用填写
                .setContent(nikename)
                // 提示可以不用填写
                //.setHint(nikename)
                // 确定按钮文本
                .setConfirm(getString(R.string.common_confirm))
                // 设置 null 表示不显示取消按钮
                .setCancel(getString(R.string.common_cancel))
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setListener(new InputDialog.OnListener() {
                    @Override
                    public void onConfirm(BaseDialog dialog, String content) {
                        toast("确定了：" + content);
                        stvModifyNikename.setRightString(content);
                        updateProfile();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        toast("取消了");
                    }
                });
        dialog.show();
    }

    private void updateProfile() {
        HashMap<String, Object> hashMap = new HashMap<>();

        // 头像
        if (!TextUtils.isEmpty(mIconUrl)) {
            hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_FACEURL, mIconUrl);
        }

        // 昵称
        String nickName = stvModifyNikename.getRightString();
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_NICK, nickName);

        // 个性签名
        //String signature = mModifySignatureView.getContent();
        //hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_SELFSIGNATURE, signature);

        // 地区
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_LOCATION, "sz"); // TODO 不加SDK会有个崩溃

        // 加我验证方式
        //String allowType = mJoinTypeIdList.get(mJoinTypeIndex);
        //hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_ALLOWTYPE, allowType);

        TIMFriendshipManager.getInstance().modifySelfProfile(hashMap, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                toast("设置失败，code" + i + ", desc = " + s);
                log("modifySelfProfile onError:code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess() {
                toast("设置完成");
                log("modifySelfProfile success");
            }
        });
    }


    //更新图片
    public void updatePic() {
        SpDoctor.setFACE_URL(mIconUrl);
        setImageIntoView();
        updateProfile();
    }

    /**
     把头像设置到view上
     可以时url/本地路径
     */
    private void setImageIntoView() {
        RequestOptions requestOptions = new RequestOptions()
                .circleCrop()
                .placeholder(mIvHead.getDrawable() == null ? getResources().getDrawable(R.drawable.me_head) : mIvHead.getDrawable())
                .dontAnimate()
                .error(R.drawable.me_head)
                .override(240, 240)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE);

        Glide.with(this)
                .asBitmap()
                .load(mIconUrl)
                .apply(requestOptions)
                .transition(BitmapTransitionOptions.withCrossFade(400))
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        toast("设置失败");
                        loge(e.getMessage());
                        mRlHeadBg.setBackgroundResource(R.drawable.me_head_bg);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        mIvHead.setImageBitmap(resource);
                        //压缩后模糊设置背景
                        Bitmap compress = ImageUtils.compressBySampleSize(resource, 8);
                        Bitmap bitmap = ImageUtils.renderScriptBlur(compress, 20);
                        mRlHeadBg.setBackground(ImageUtils.bitmap2Drawable(bitmap));
                        return true;//返回true之后.into()方法无效
                    }
                })
                .into(mIvHead);
    }


    void showMessage() {
        new MessageDialog.Builder(getAttachActivity())
                .setMessage("你确定要退出小科？")
                // 确定按钮文本
                .setConfirm(getString(R.string.common_confirm))
                // 设置 null 表示不显示取消按钮
                .setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setListener(new MessageDialog.OnListener() {

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        //做登出操作
                        mPresenter.logout();
                        SpSetting.setLogin(false);

                        ActivityUtils.startActivity(LoginActivity.class);
                        ActivityUtils.finishAllActivities();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                    }
                })
                .show();
    }

    void showWarning(String text) {
        // 警告对话框
        new ToastDialog.Builder(getAttachActivity())
                .setType(ToastDialog.Type.WARN)
                .setMessage(TextUtils.isEmpty(text) ? "警告" : text)
                .show();
    }

    void showMenuChoose() {
        String[] items = new String[]{"拍照", "进入相册"};
        List<String> data = Arrays.asList(items);
        // 居中选择框
        new MenuDialog.Builder(getAttachActivity())
                .setGravity(Gravity.CENTER)
                .setCancel(null)
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(data)
                .setListener(new MenuDialog.OnListener<String>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        toast("点击了" + string);
                        switch (position) {
                            case 0:
                                PictureSelectUtils.getByCamera(getAttachActivity());
                                break;
                            case 1:
                                PictureSelectUtils.getByAlbum(getAttachActivity());
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                        toast("取消了");
                    }
                })
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                //TODO 这里应该是上传图片，然后拿到url,设置给 mIconUrl
                mIconUrl = data.getStringExtra(PictureSelector.PICTURE_PATH);
                updatePic();
                /*使用 Glide 加载图片，由于裁剪后的图片地址是相同的，所以不能从缓存中加载*/
                /*RequestOptions requestOptions = RequestOptions
                        .circleCropTransform()
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true);
                Glide.with(this).load(picturePath).apply(requestOptions).into(mIvImage);*/
            }
        }

    }

    @Override
    public void failSaveIsReceiveMsg() {
        stvReceivedMsg.setSwitchIsChecked(!stvReceivedMsg.getSwitchIsChecked());
    }

    @Override
    public void failSaveIsInquiry() {
        stvInquiry.setSwitchIsChecked(!stvInquiry.getSwitchIsChecked());
    }

    @Override
    public void completeReceive() {
        completeView(stvReceivedMsg);
        stvReceivedMsg.setSwitchCheckedChangeListener(receiveMsgSwitchListener);
    }

    @Override
    public void completeInquiry() {
        completeView(stvInquiry);
        stvInquiry.setSwitchCheckedChangeListener(inquirySwitchListener);
    }

    @Override
    public void logoutSuccess() {

    }

    @Override
    public void logoutFailed() {

    }
}
